package com.uyaer.wheel.plus
{
	import com.uyaer.wheel.common.Config;
	
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;

	public class Audio
	{
		private static var m_instance:Audio;
		private var home:Sound;
		private var homeChannel:SoundChannel;
		private var gaming:Sound;
		private var gamingChannel:SoundChannel;
		private var hit:Sound;
		private var hitChannel:SoundChannel;
		private var isPlaying:Boolean = false;
		public function Audio()
		{
		}
		
		public static function get me():Audio{
			return m_instance ||= new Audio();
		}
		
		private function getURI(name:String):String{
			return Config.audioSource+"/"+name+".mp3";
		}
		
		
		public function playHome():void{
			if(!Config.MUSIC)return;
			if(!home){
				home = new Sound(new URLRequest(getURI("home")));
			}
			if(homeChannel)homeChannel.stop();
			homeChannel = home.play(0,int.MAX_VALUE);
		}
		
		public function stopHome():void{
			homeChannel && homeChannel.stop();
			homeChannel = null;
		}
		
		public function playGaming():void{
			if(!Config.MUSIC)return;
			if(!gaming){
				gaming = new Sound(new URLRequest(getURI("gaming")));
			}
			if(gamingChannel)gamingChannel.stop();
			gamingChannel = gaming.play(0,int.MAX_VALUE);
		}
		
		public function stopGaming():void{
			gamingChannel && gamingChannel.stop();
			gamingChannel = null;
		}
		
		public function playHit():void{
			if(!Config.MUSIC)return;
			if(!hit){
				hit = new Sound(new URLRequest(getURI("hit")));
			}
			if(!isPlaying){
				hitChannel = hit.play(0,1);
				hitChannel.addEventListener(Event.SOUND_COMPLETE,onPlayOver);
			}else{
				hitChannel.removeEventListener(Event.SOUND_COMPLETE,onPlayOver);
				hitChannel = hit.play(0,1);
				hitChannel.addEventListener(Event.SOUND_COMPLETE,onPlayOver);
			}
			isPlaying = true;
		}
		
		private function onPlayOver(e:Event):void{
			hitChannel.removeEventListener(Event.SOUND_COMPLETE,onPlayOver);
			isPlaying = false;
		}
	}
}